<!--
 * @Author: 星孑
 * @Date: 2022-04-07 16:57:48
 * @LastEditors: 星孑
 * @LastEditTime: 2022-04-08 11:18:40
 * @FilePath: /admin/src/components/fileUpload.vue
 * @Description: 文件上传组件（单张）
-->

<template>
  <el-upload
    action=""
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :accept="accept"
    :on-change="handleChange"
    :http-request="upload"
  >
    <div v-loading="uploadLoading" class="img-box">
      <div v-if="hasDel && imageUrl" class="delete" @click.stop="del">
        <i class="el-icon-delete" />
      </div>
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </div>
  </el-upload>
</template>
<script>
/**
 * @param {String} imageUrl    图片地址,需要设置可更新.sync
 */

import request from '@/utils/request'

export default {
  props: {
    imageUrl: {
      type: String,
      default: ''
    },
    format: {
      type: Array,
      default() {
        return ['image']
      }
    },
    hasDel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      imgTypes: ['image/png', 'image/jpeg', 'image/tif', 'image/bmp'],
      gifTypes: ['image/gif'],
      videoTypes: ['video/avi', 'video/mp4'],
      fileList: [],
      uploadLoading: false,
      accept: ''
    }
  },
  created() {
    if (this.format.includes('video')) {
      this.accept = [...this.imgTypes, ...this.gifTypes, ...this.videoTypes].join(',')
    } else {
      this.accept = [...this.imgTypes, ...this.gifTypes].join(',')
    }
  },
  methods: {
    del() {
      this.$emit('del')
    },
    handleAvatarSuccess() {},
    handleChange(file, fileList) {
      this.fileList = fileList
      this.uploadLoading = true
    },
    upload(param) {
      const fileSize = Math.round((param.file.size * 100) / (1024 * 1024)) / 100
      // const types = ["png", "jpg", "jpeg", "PNG", "JPEG", "JPG"]
      // const fileName = param.file.name

      // const isType = types.some((type) => {
      //   return param.file.type.indexOf(type) >= 0
      // })
      const fileType = param.file.type
      if (this.imgTypes.includes(fileType)) {
        if (fileSize > 5) {
          this.$message({
            type: 'warning',
            message: '图片大小不可超过5MB !'
          })
          this.uploadLoading = false
          return
        }
      } else if (this.gifTypes.includes(fileType)) {
        if (fileSize > 10) {
          this.$message({
            type: 'warning',
            message: 'GIF大小不可超过10MB !'
          })
          this.uploadLoading = false
          return
        }
      } else if (this.videoTypes.includes(fileType)) {
        if (fileSize > 30) {
          this.$message({
            type: 'warning',
            message: '视频大小不可超过30MB !'
          })
          this.uploadLoading = false
          return
        }
      }

      if (this.uploadValidate) {
        if (this.uploadValidate()) {
          this.fileUpload(param)
        }
      } else {
        this.fileUpload(param)
      }
      // if (fileName.length && fileName.length >= 100) {
      //   this.$message({
      //     type: "warning",
      //     message: "文件名不可超过100个字符 !",
      //   })
      //   return
      // }
    },
    fileUpload(param) {
      const file = new FormData()
      file.append('file', param.file)
      file.append('fileName', param.file.name)
      file.append('description', '')
      file.append('tagIds', [])
      request({
        url: '/member/file/upload/file',
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        data: file
      })
        .then((res) => {
          this.uploadLoading = false
          if (res) {
            this.$emit('update:image-url', res)
          }
        })
        .catch((e) => {
          this.uploadLoading = false
        })
    }
  }
}

</script>
<style lang='scss' scoped>
.img-box {
  position: relative;
  width: 120px;
  height: 120px;
  line-height: 120px;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  overflow: hidden;
  border: 1px dashed #ddd;

  img {
    width: 100%;
    vertical-align: middle;
  }

  ::v-deep .el-loading-spinner {
    margin-top: -50%;
  }

  .delete {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba($color: #000000, $alpha: .2);
    text-align: center;
    color: #fff;
    height: 24px;
    line-height: 24px;
    cursor: pointer;
  }
}
</style>
